jQuery(document).ready(function($) {
    domain = window.location.protocol + "//" + window.location.host;
    
//    $('#main-nav li').mouseover(function(){
//       var catid=$(this).attr('catid');
//       $('#hid-catid-item-'+catid).show();
//    });
//    $('#main-nav li').mouseleave(function(){         
//         setTimeout(function(){
//             $('.hid-catid-item').hide();
//         }, 500); 
//     });   
    
     $('#show-cart').mouseover(function(){
        jQuery('#carts').show(); 
     });   
     $('#show-cart').mouseleave(function(){
        jQuery('#carts').hide(); 
     });   
    
    $('.btn-order').bind('click', function(){        
        var nid=$(this).attr('nid');
         $.ajax({
            url: domain + '/ajax-process?action=popupProduct',
            data: {nid: nid},
            asyn:true,
            success: function(response) {                
                var x = '<div id="product-info" class="clock product-popup"><span class="close-popup">[Close]</span>'+response+'</div>';
                $('#page-wrapper').append(x);        
                reload();
                $('body').addClass('shown-popup');
            }
        });        
    });  
    
    $('.close-popup').live('click', function(){
       closePopupProductInfo();
    });
    
    $('#txt-custom-search').keyup(function(){
        // only show result div when ajax returns data
        $('#custom-search-result').hide();
       var key = $(this).val();
        jQuery.ajax({
            url: domain + '/ajax-process?action=custom_search',
            data: {key:key},
            asyn:true,
            success: function(response) {
                $('#custom-search-result').html(response);
                // ajax returns data
                if($.trim( $('#custom-search-result').html()).length) {
                    $('#custom-search-result').show();
                }
            }
        });

    });
});

function closePopupProductInfo(){
    jQuery('#product-info.product-popup').remove();
    jQuery('body').removeClass('shown-popup');    
}

function reload(){
    jQuery('#product-detail-carousel').jcarousel({
        //visible:1,
        vertical:true
    });    
        
    var options = {  
            zoomType: 'standard',
            lens:true,
            preloadImages: false,
            alwaysOn:false
    };  
    
    jQuery('.zoom-wrapper').each(function(){
        jQuery(this).jqzoom(options);  
    });
    
    jQuery('#product-info .zoom-wrapper').hide();
    jQuery('#product-info .zoom-wrapper[index=0]').show();       
    jQuery('#product-thumbnails li img').bind('mouseenter', function(){
        var index = jQuery(this).attr('index');
        jQuery('#product-info .zoom-wrapper').hide();
        jQuery('#product-info .zoom-wrapper[index='+index+']').show();        
    });
    
    // select tab 
     jQuery('#detail-info .tab-info').hide();
     jQuery('#detail-info .tab-info[tab=1]').show();
     
     jQuery('#detail-info .tab-title').bind('click', function(){
         var tab = jQuery(this).attr('tab');
         
         jQuery('#detail-info .tab-title').removeClass('active');
         jQuery(this).addClass('active');
         
         jQuery('#detail-info .tab-info').hide();
         jQuery('#detail-info .tab-info[tab='+tab+']').show();
     });
     
     
     //add product to cart
     jQuery('#detail-info .color').bind('click', function(){
         jQuery('#detail-info .color').removeClass('selected');
         jQuery(this).addClass('selected');         
     });
     
     jQuery('#detail-info .size').bind('click', function(){
         jQuery('#detail-info .size').removeClass('selected');
         jQuery(this).addClass('selected');         
     });
     
     jQuery('#detail-info #btnAddToCart').bind('click', function(){
        // 1. filter data
        var nid = jQuery('#detail-info #txtAmount').attr('nid');
        var amount = jQuery('#detail-info #txtAmount').val();
        var color = jQuery('#detail-info .color.selected').attr('color-value');
        var size = jQuery('#detail-info .size.selected').attr('size-value');
//        if(jQuery.isNumeric(amount)!=true){
//            alert('Nhập số lượng');
//            return false;
//        }
        
        // 2. submit request
        jQuery.ajax({
            url: domain + '/ajax-process?action=addToCart',
            data: {nid: nid, amount:amount, color:color, size:size},
            success: function(response) {
                if (response == '-'){    // anonymous
                    alert_user_not_login();
                    return;
                }else{ // successful: reload block cart
                    closePopupProductInfo();        
                    alert('Đã thêm sản phẩm vào giỏ hàng');
                    reload_block_cart();
                }
            }
        });
     });          
     
     jQuery('#ordered-products .btn-remove').live('click', function(){
        var remove = confirm('Bạn có chắc muốn xóa sản phẩm khỏi giỏ hàng?');
        if(remove){
            var nid = jQuery(this).attr('pnid');
            jQuery.ajax({
                url: domain + '/ajax-process?action=removeFromCart',
                asyn:true,
                data: {nid: nid},            
                success: function(response) {
                    if (response == '-'){    // anonymous
                        alert_user_not_login();
                        return;
                    }else{// success
                        window.location = domain+'/carts';
                    }
                }
            });
        }        
     });    
}

function reload_block_cart() {
    jQuery.ajax({
        url: domain + '/ajax-process?action=reloadBlockCarts',
        asyn: true,
        success: function(response) {
            console.log(response);
            jQuery('#carts').html(response);
            jQuery('#carts').show();
        }
    });
}

/**
 * Page: product detail
 * */
jQuery(document).ready(function($) {
    
    domain = window.location.protocol + "//" + window.location.host;
    
    reload();          
        
     
     // jcarousel in related products
     jQuery('.related-products').jcarousel({
       // visible:1,
        vertical:true,
        scroll: 1
    });
    
    $('#btnSendComment').bind('click', function(){
        var title = $('#txtCommentTitle').val();
        var body = $('#txtCommentBody').val();
        var nid = $('#btnSendComment').attr('nid');
        $.ajax({
            url: domain + '/ajax-process?action=addComment',
            data: {title: title, body:body, nid:nid},
            asyn:true,
            success: function(response) {
                if (response == '-'){    // anonymous
                    alert_user_not_login();
                    return;
                }else if (response == '0'){ // error
                    alert('Error');   
                }else{   // success => add this comment to current page
                    $('#list-comments').append(response);
                    $('#txtCommentTitle').val("");
                    $('#txtCommentBody').val("");
                }                    
            }
        });
    });
    
});


function alert_user_not_login(){
    alert('Bạn cần đăng nhập trước');    
}


/**
 * Page: carts
 * */
jQuery(document).ready(function($) {
    // input amount
    jQuery('.input-amount').change(function(){
       var amount = jQuery(this).val();
       var reg = /^\d+$/;
       if(reg.test(amount)){ // update carts in session & in UI
           var nid= jQuery(this).attr('nid');
           update_carts(nid, amount, "");
       }else{
           alert('Nhập số lượng');
       }
    });
});

function update_carts(nid, amount, size) {
    jQuery.ajax({
        url: domain + '/ajax-process?action=updateCart',
        data: {nid:nid, amount:amount, size:size},
        asyn: true,
        success: function(response) {
            if(response!=0){ // no error
                // re-calculate amount value in case update amount
                var total_cost = 0;
                jQuery('.input-amount').each(function(){
                    nid = jQuery(this).attr('nid');
                    amount = jQuery('.input-amount[nid='+nid+']').val();
                    var price = jQuery('.price[nid='+nid+']').attr('price');
                    var row_price = amount * price;
                    jQuery('.row_price[nid='+nid+']').text(display_price(row_price));
                    total_cost += row_price;
                });
                jQuery('#total-cost .price').text(display_price(total_cost));
            }
        }
    });
}


function display_price(nStr)
{
  nStr += '';
  x = nStr.split('.');
  x1 = x[0];
  x2 = x.length > 1 ? '.' + x[1] : '';
  var rgx = /(\d+)(\d{3})/;
  while (rgx.test(x1)) {
    x1 = x1.replace(rgx, '$1' + '.' + '$2');
  }
 
  var result = x1+x2;
  result +='.000 VNĐ';
  console.log(result);
    return result;
}
  

/**
 * Page: payment
 * */
jQuery(document).ready(function($) {
    $('.step .step-content').hide();    
    $('.step .step-content.active').show();
    
    $('.step .change-step').bind('click',function(){
        $('.step .step-content').hide();    
        $(this).parents('.step').children('.step-content').show();
    });
    
    $('.step .next-step').bind('click',function(){
        var next = $(this).attr('next');
        $('.step .step-content').hide();    
        $('.step-'+next+' .step-content').show();    
        
    });
    
    $('#transform-2').click(function(){
       var checked = $(this).attr('checked');
       if(checked==true){
           $('.step-2 .next-step').attr('next', 3);
       }
    });
    $('#transform-1').click(function(){
       var checked = $(this).attr('checked');
       if(checked==true){
           $('.step-2 .next-step').attr('next', 4);
       }
    });
});
  